package wpwork.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import wpwork.base.ActionResult;
import wpwork.entity.KshMessageEntity;
import wpwork.model.*;
import wpwork.service.IKshMessageService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/example/message")
public class KshMessageController {

    @Autowired
    private IKshMessageService messageService;

    // 新增消息
    @PostMapping
    public boolean save(@RequestBody KshMessageEntity message) {
        return messageService.save(message);
    }

    // 批量新增
    @PostMapping("/batch")
    public boolean saveBatch(@RequestBody List<KshMessageEntity> messages) {
        return messageService.saveBatch(messages);
    }

    // 根据ID删除
    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable String id) {
        return messageService.removeById(id);
    }

    // 批量删除
    @DeleteMapping("/batch")
    public boolean deleteBatch(@RequestBody List<String> ids) {
        return messageService.removeByIds(ids);
    }

    // 根据ID修改
    @PutMapping
    public boolean update(@RequestBody KshMessageEntity message) {
        return messageService.updateById(message);
    }

    // 批量修改
    @PutMapping("/batch")
    public boolean updateBatch(@RequestBody List<KshMessageEntity> messages) {
        return messageService.updateBatchById(messages);
    }

    // 根据ID查询
    @GetMapping("/{id}")
    public KshMessageEntity getById(@PathVariable String id) {
        return messageService.getById(id);
    }

    // 查询所有
    @GetMapping("/all")
    public List<KshMessageEntity> getAll() {
        return messageService.list();
    }

    // 分页查询
    @GetMapping("/page")
    public IPage<KshMessageEntity> getPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size) {
        Page<KshMessageEntity> page = new Page<>(current, size);
        return messageService.page(page);
    }

    // 条件查询示例：根据发送人和接收人查询
    @GetMapping("/query")
    public List<KshMessageEntity> queryByCondition(
            @RequestParam(required = false) String fromUserId,
            @RequestParam(required = false) String toUserId) {
        QueryWrapper<KshMessageEntity> wrapper = new QueryWrapper<>();

        if (fromUserId != null && !fromUserId.isEmpty()) {
            wrapper.eq("f_fromuserid", fromUserId);
        }

        if (toUserId != null && !toUserId.isEmpty()) {
            wrapper.eq("f_touserid", toUserId);
        }

        return messageService.list(wrapper);
    }

    // 条件查询示例：查询未读消息
//    @GetMapping("/unread")
//    public List<KshMessageEntity> getUnreadMessages(@RequestParam String toUserId) {
//        QueryWrapper<KshMessageEntity> wrapper = new QueryWrapper<>();
//        wrapper.eq("f_touserid", toUserId)
//                .eq("f_isread", 0)
//                .eq("f_delete_mark", 0);
//
//        return messageService.list(wrapper);
//    }

    // 标记消息为已读
    @PutMapping("/read/{id}")
    public boolean markAsRead(@PathVariable String id) {
        KshMessageEntity message = new KshMessageEntity();
        message.setId(id);
        message.setIsRead(1);
        message.setReadTime(LocalDateTime.now());

        return messageService.updateById(message);
    }

    /**
     * 1. 发送消息接口
     * POST /api/message/send
     */
    @PostMapping("/send")
    public ActionResult sendMessage(@Validated @RequestBody SendMessageRequestDTO request) {
        try {
            boolean result = messageService.sendMessage(request);
            return ActionResult.success("消息发送成功");
        } catch (Exception e) {
            return ActionResult.fail("消息发送失败: " + e.getMessage());
        }
    }

    /**
     * 2. 消息已读接口
     * PUT /api/message/mark-read
     */
    @PutMapping("/mark-read")
    public ActionResult<Boolean> markMessagesAsRead(@Validated @RequestBody MarkAsReadRequestDTO request) {
        try {
            boolean result = messageService.markMessagesAsRead(request);
            return ActionResult.success("消息标记为已读成功");
        } catch (Exception e) {
            return ActionResult.fail("标记已读失败: " + e.getMessage());
        }
    }

    /**
     * 3. 查询个人或群组消息
     * POST /api/message/query
     */
    @PostMapping("/query")
    public ActionResult<List<MessageResponseDTO>> queryMessages(@Validated @RequestBody QueryMessageRequestDTO request) {
        try {
            List<KshMessageEntity> messages = messageService.queryMessages(request);
            List<MessageResponseDTO> response = messages.stream()
                    .map(this::convertToResponse)
                    .collect(Collectors.toList());
            return ActionResult.success(response);
        } catch (Exception e) {
            return ActionResult.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 4. 查询未读消息
     * GET /api/message/unread/{userId}
     */
    @GetMapping("/unread/{userId}")
    public ActionResult<List<MessageResponseDTO>> getUnreadMessages(@PathVariable String userId) {
        try {
            List<KshMessageEntity> messages = messageService.getUnreadMessages(userId);
            List<MessageResponseDTO> response = messages.stream()
                    .map(this::convertToResponse)
                    .collect(Collectors.toList());
            return ActionResult.success(response);
        } catch (Exception e) {
            return ActionResult.fail("查询失败: " + e.getMessage());
        }
    }

    /**
     * 首页查询个人或群组消息
     * POST /api/message/query
     */
    @PostMapping("/instantMessage")
    public ActionResult<List<MessageResponseDTO2>> instantMessage(@RequestParam String receivePerson,
                                                                  @RequestParam String sendPerson,
                                                                  @RequestParam String sendType,
                                                                  @RequestParam String keyword,
                                                                  @RequestParam String startTime,
                                                                  @RequestParam String endTime) {
        List<MessageResponseDTO2> messages = messageService.instantMessage(receivePerson, sendPerson, sendType, keyword, startTime, endTime);
        return ActionResult.success(messages);
    }

    @Operation(summary = "删除")
    @PostMapping("/deleteDataOne")
    public ActionResult<?> deleteDataOne(@RequestParam String id) {
        boolean b = messageService.removeById(id);
        if (b){
            return ActionResult.success("删除成功");
        }else{
            return ActionResult.fail("删除失败");
        }
    }

    /**
     * 实体类转响应DTO
     */
    private MessageResponseDTO convertToResponse(KshMessageEntity message) {
        MessageResponseDTO response = new MessageResponseDTO();
        response.setId(message.getId());
        response.setType(message.getType());
        response.setGroupId(message.getGroupId());
        response.setFromUserId(message.getFromUserId());
        response.setToUserId(message.getToUserId());
        response.setMessage(message.getMessage());
        response.setIsRead(message.getIsRead());
        response.setReadTime(message.getReadTime());
        response.setRemark(message.getRemark());
        response.setCreatorTime(message.getCreatorTime());
        return response;
    }
}